package com.coder.rental.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.coder.rental.entity.CarInfo;
import com.coder.rental.entity.Order;
import com.coder.rental.mapper.CarInfoMapper;
import com.coder.rental.mapper.OrderMapper;
import com.coder.rental.service.IOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

/**
 * <p>
 * 出租订单 服务实现类
 * </p>
 *
 * @author zhaojj
 * @since 2025-01-10
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {

    @Resource
    private CarInfoMapper carInfoMapper;
    @Override
    public boolean insert(Order order) {
        // 当前车辆的状态，由未租改为已租
        Integer autoId = order.getAutoId();
        CarInfo carInfo = carInfoMapper.selectById(autoId);
        carInfo.setStatus(1);
        carInfoMapper.updateById(carInfo);
        // 生成订单编号
        String format = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS").format(LocalDateTime.now());
        order.setOrderNum(format);
        order.setRentalTime(LocalDateTime.now());
        return baseMapper.insert(order)>0;
    }

    @Override
    public Page<Order> searchUnfinished(Page<Order> page, Order order) {
        return baseMapper.searchUnfinished(page,order);
    }

    @Override
    public boolean returnCar(Order order,Integer maintainMileage) {
        try {
            // 修改车辆的状态
            Integer carId = order.getAutoId();
            CarInfo carInfo = carInfoMapper.selectById(carId);
            carInfo.setStatus(0);
            // 增加车辆行驶里程
            carInfo.setMileage(order.getReturnMileage());
            // 增加应保次数
            carInfo.setExpectedNum(carInfo.getMileage() / maintainMileage);
            carInfoMapper.updateById(carInfo);
            // 更新订单
            baseMapper.updateById(order);
            return true;
        }
        catch (Exception e){
            throw new RuntimeException();
        }
    }

    @Override
    public Page<Order> search(Page<Order> page,Order order) {
        return baseMapper.search(page,order);
    }

    @Override
    public long depositReturn(Integer autoId) {
        return baseMapper.countViolation(autoId);
    }
}
